import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { TMenu } from 'src/entities/menu.entity';
import { Response } from 'src/utils/response';
import { formatTime, beanCopyArray, beanCopy } from 'src/utils';
import { InjectRepository } from '@nestjs/typeorm';
import { USER_PERMISSION_MAP } from 'src/common/const';
import { MenuAddDto } from './dto/menu-add.dto';
import { MenuUpdateDto } from './dto/menu-update.dto';
import { MenuListDto } from './dto/menu-list-dto';
import { MenuListVO } from './vo/menu-list.vo';
import { RouteInterface } from './menu.interface';

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(TMenu)
    private readonly menuRepository: Repository<TMenu>,
  ) {}

  // 获取路由列表
  async getRouteListService({ permission }: MenuListDto) {
    if (!permission) {
      return Response.error({ message: '当前用户无权限' });
    }
    const permissionString = USER_PERMISSION_MAP[permission];
    const routes = await this.menuRepository.find({
      where: { delFlag: 0 },
    });
    const result = routes.filter((route) => {
      return route.permission.includes(permissionString);
    });
    const vo = new MenuListVO();
    const data = beanCopyArray<MenuListVO>(vo, result);
    data.forEach((menu) => {
      formatTime(menu, ['createdAt']);
    });
    return Response.success({ data: data });
  }

  // 获取顶级路由列表
  async getPrintList() {
    const routes = await this.menuRepository.find({
      where: { delFlag: 0 },
    });
    const result = routes
      .filter((route) => {
        return !route.pid;
      })
      .map((route) => ({
        name: route.name,
        path: route.path,
        component: route.component,
        isSidebar: route.isSidebar,
        meta: route.meta,
        id: route.id,
      }));
    return Response.success({ data: result });
  }

  // 添加
  async addRoute(data: MenuAddDto) {
    const dto = new MenuAddDto();
    const addDto = beanCopy(dto, data);
    const routeInfo: any = {
      ...addDto,
      meta: JSON.parse(JSON.stringify(data.meta || {})),
    };
    try {
      const route = this.menuRepository.create(routeInfo);
      await this.menuRepository.save(route);
      return Response.success({ message: '添加成功' });
    } catch (e) {
      return Response.error({ message: e });
    }
  }

  // 更新
  async updateRoute(data: MenuUpdateDto) {
    if (!data.id) {
      return Response.error({ message: '未传递数据id' });
    }
    const dto = new MenuUpdateDto();
    const updateDto = beanCopy(dto, data);
    const route = await this.menuRepository.findOne({
      where: { id: updateDto.id, delFlag: 0 },
    });
    if (!route) {
      return Response.error({ message: '路由不存在' });
    }
    // @ts-ignore
    await this.menuRepository.update(updateDto.id, updateDto);
    return Response.success({ message: '更新成功' });
  }

  // 删除
  async removeRoute(id: number) {
    await this.menuRepository.update(id, { delFlag: 1 });
    return Response.success({ message: '删除成功' });
  }
}
